package com.pethospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pethospital.dto.PetDTO;
import com.pethospital.entity.Pet;
import com.pethospital.exception.BusinessException;
import com.pethospital.mapper.PetMapper;
import com.pethospital.service.PetService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class PetServiceImpl extends ServiceImpl<PetMapper, Pet> implements PetService {

    @Override
    public Long add(PetDTO petDTO, Long userId) {
        Pet pet = new Pet();
        BeanUtils.copyProperties(petDTO, pet);
        
        pet.setUserId(userId);
        pet.setCreateTime(LocalDateTime.now());
        pet.setUpdateTime(LocalDateTime.now());
        
        save(pet);
        return pet.getId();
    }

    @Override
    public boolean update(PetDTO petDTO, Long userId) {
        // 检查宠物是否存在且属于当前用户
        Pet pet = getOne(new LambdaQueryWrapper<Pet>()
                .eq(Pet::getId, petDTO.getId())
                .eq(Pet::getUserId, userId));
        
        if (pet == null) {
            throw new BusinessException("宠物不存在或不属于当前用户");
        }
        
        BeanUtils.copyProperties(petDTO, pet);
        pet.setUpdateTime(LocalDateTime.now());
        
        return updateById(pet);
    }

    @Override
    public boolean delete(Long id, Long userId) {
        // 检查宠物是否存在且属于当前用户
        Long count = count(new LambdaQueryWrapper<Pet>()
                .eq(Pet::getId, id)
                .eq(Pet::getUserId, userId));
        
        if (count == 0) {
            throw new BusinessException("宠物不存在或不属于当前用户");
        }
        
        return removeById(id);
    }

    @Override
    public Pet getById(Long id) {
        return super.getById(id);
    }

    @Override
    public Page<Pet> pageByUserId(Long userId, int page, int size) {
        return page(new Page<>(page, size), new LambdaQueryWrapper<Pet>()
                .eq(Pet::getUserId, userId)
                .orderByDesc(Pet::getCreateTime));
    }
} 